package mapred.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TermCounter implements Configurable<String, Long> {

    private Map<String, Long> map = new HashMap<String, Long>();

    @Override
    public boolean contains(String key) {
        return map.containsKey(key);
    }

    @Override
    public Long get(String key) {
        return map.get(key);
    }

    @Override
    public void remove(String key) {
        map.remove(key);
    }

    @Override
    public void set(String key, Long value) {
        if (!key.trim().isEmpty()) {
            map.put(key, value);
        }
    }

    @Override
    public int size() {
        return map.size();
    }

    public void add(String... keys) {
        for (String key : keys) {
            if (this.contains(key)) {
                this.set(key, this.get(key) + 1);
            } else {
                this.set(key, 1L);
            }
        }
    }

    @Override
    public Iterator<String> iterator() {
        return map.keySet().iterator();
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (String s : this) {
            sb.append(s);
            sb.append(" ");
            sb.append(this.get(s));
            sb.append("\t");
        }
        return sb.toString().trim();
    }

    public void add(TermCounter other) {
        for (String s : other) {
            this.add(s, other.get(s));
        }
    }

    public void add(String text, long value) {
        if (this.contains(text)) {
            this.set(text, this.get(text) + value);
        } else {
            this.set(text, value);
        }
    }

    public static TermCounter parse(String s) {
        TermCounter ret = new TermCounter();
        for (String t : s.split("\t")) {
            if (!t.isEmpty()) {
                try {
                    int pos = t.lastIndexOf(" ");
                    String term = t.substring(0, pos);
                    long count = Long.parseLong(t.substring(pos + 1));
                    ret.add(term, count);
                } catch (Exception e) {
                    
                }
            }
        }
        return ret;
    }
    
}
